package com.example.homeworkmanagement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.homeworkmanagement.dto.AssignmentsAndTeachersAndCoursesAndTeachersAndSubmissionsDTO;
import com.example.homeworkmanagement.dto.AssignmentsAndTeachesAndCoursesAndTeachersDTO;
import com.example.homeworkmanagement.dto.CoursesAndTeachesDTO;
import com.example.homeworkmanagement.pojo.Assignments;
import com.example.homeworkmanagement.mapper.AssignmentsMapper;
import com.example.homeworkmanagement.pojo.Attachments;
import com.example.homeworkmanagement.pojo.Submissions;
import com.example.homeworkmanagement.service.AssignmentsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.homeworkmanagement.service.AttachmentsService;
import com.example.homeworkmanagement.service.SubmissionsService;
import com.example.homeworkmanagement.utils.DocxUtil;
import com.example.homeworkmanagement.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 拒绝加班
 * @since 2025-05-25
 */
@Service
public class AssignmentsServiceImpl extends ServiceImpl<AssignmentsMapper, Assignments> implements AssignmentsService {
    @Autowired
    private AttachmentsService attachmentsService;

    @Autowired
    private AssignmentsMapper assignmentsMapper;

    @Autowired
    private SubmissionsService submissionsService;

    @Override
    public ResultVO<Assignments> deleteAssignment(Integer assignmentId) {
        try {
            if (assignmentId == null) {
                return ResultVO.fail("作业不能为空");
            }

            Assignments assignment =this.getById(assignmentId);
            if (assignment == null) {
                return ResultVO.fail("作业不存在");
            }

            //检查作业是否有附件，需要一起删除
            if(assignment.getAttachment()!=null){
                attachmentsService.deleteAttachment(assignment.getAttachment());
            }

            //以及删除学生作业记录以及提交的附件
            QueryWrapper<Submissions> queryWrapper = new QueryWrapper<>();
            //获取学生提交的作业列表--获取学生id
            queryWrapper.eq("assignment_id",assignmentId);
            List<Submissions> list = submissionsService.list(queryWrapper);

            //逐一删除学生的提交作业记录
            for (Submissions submissions: list){
                String studentId1=submissions.getStudentId();
                submissionsService.deleteSubmission(assignmentId,studentId1);
            }

            boolean success = removeById(assignmentId);
            return (success) ? ResultVO.success("作业删除成功", assignment) : ResultVO.fail("作业删除失败");
        } catch (Exception e) {
            return ResultVO.fail("删除作业异常: " + e.getMessage());
        }
    }

    @Override
    public ResultVO<Assignments> updateAssignment(Integer assignmentId, Integer teachId, String title, String content, Date startTime, Date dueTime, String state, MultipartFile file) {
        try {
            // 校验作业ID（更新场景必须存在）
            if (assignmentId == null) {
                return ResultVO.fail("作业ID不可为空");
            }
            // 查询原作业记录
            Assignments originalAssignment = this.getById(assignmentId);
            if (originalAssignment == null) {
                return ResultVO.fail("作业不存在，无法更新");
            }
            Integer attachmentId = originalAssignment.getAttachment(); // 原有附件ID
            if (file != null && !file.isEmpty()) {
                // 上传新附件
                String filename = file.getOriginalFilename();
                if (filename != null && filename.toLowerCase().endsWith(".docx")) {
                    try {
                        // 解析并保存新附件
                        Attachments newAttachment = DocxUtil.convertToAttachment(file);
                        if (attachmentsService.save(newAttachment)) {
                            //新附件ID
                            attachmentId = newAttachment.getAttachment();
                            // 删除旧附件（如果存在）
                            if (originalAssignment.getAttachment() != null) {
                                attachmentsService.removeById(originalAssignment.getAttachment());
                            }
                        } else {
                            return ResultVO.fail("新附件保存失败");
                        }
                    } catch (IOException e) {
                        return ResultVO.fail("附件解析失败");
                    }
                } else {
                    return ResultVO.fail("仅支持上传.docx格式的新附件");
                }
            }
            Assignments updatedAssignment = new Assignments();
            updatedAssignment.setAssignmentId(assignmentId);
            updatedAssignment.setTeachId(teachId != null ? teachId : originalAssignment.getTeachId());
            updatedAssignment.setTitle(title != null && !title.trim().isEmpty() ? title : originalAssignment.getTitle());
            updatedAssignment.setContent(content != null && !content.trim().isEmpty() ? content  : originalAssignment.getContent());
            updatedAssignment.setStartTime(startTime != null ? startTime : originalAssignment.getStartTime());
            updatedAssignment.setDueTime(dueTime != null ? dueTime : originalAssignment.getDueTime());
            updatedAssignment.setState(state != null  && !state.trim().isEmpty() ? state : originalAssignment.getState());
            updatedAssignment.setAttachment(attachmentId); // 可能为null或新ID
            boolean updateSuccess = this.updateById(updatedAssignment);
            return updateSuccess ? ResultVO.success("作业更新成功", updatedAssignment) : ResultVO.fail("作业更新失败，可能是数据冲突");

        } catch (Exception e) {
            return ResultVO.fail("系统异常：" + e.getMessage());
        }
    }

    @Override
    public ResultVO<Assignments> getAssignmentById(Integer assignmentId) {
        try {
            if (assignmentId == null) {
                return ResultVO.fail("作业ID不能为空");
            }

            Assignments assignment = this.getById(assignmentId);
            return assignment != null ?
                    ResultVO.success("查询成功", assignment) :
                    ResultVO.fail("作业不存在");
        } catch (Exception e) {
            return ResultVO.fail("查询作业异常: " + e.getMessage());
        }
    }

    @Override
    public ResultVO<List<AssignmentsAndTeachesAndCoursesAndTeachersDTO>> selectAssignmentByInfos(AssignmentsAndTeachesAndCoursesAndTeachersDTO dto,int page,int size) {
        List<AssignmentsAndTeachesAndCoursesAndTeachersDTO> list = assignmentsMapper.selectAssignmentByInfos(dto);
        if (list==null || list.isEmpty()){
            return ResultVO.fail("未查询到作业信息");
        }
        // 计算分页起始和结束索引
        int startIndex = (page - 1) * size;
        int endIndex = Math.min(startIndex + size, list.size());
        // 截取当前页的数据
        List<AssignmentsAndTeachesAndCoursesAndTeachersDTO> pageList = list.subList(startIndex, endIndex);
        int total = list.size();
        return ResultVO.success("查询成功", pageList,total);
    }

    @Override
    public ResultVO<List<AssignmentsAndTeachersAndCoursesAndTeachersAndSubmissionsDTO>> selectAssignmentAndSubmissionByInfos(AssignmentsAndTeachesAndCoursesAndTeachersDTO dto, String studentId, int page, int size) {
        List<AssignmentsAndTeachesAndCoursesAndTeachersDTO> list = assignmentsMapper.selectAssignmentByInfos(dto);
        if(list==null || list.isEmpty()){
            return ResultVO.success("未查询到作业信息");
        }
        List<AssignmentsAndTeachersAndCoursesAndTeachersAndSubmissionsDTO> dtoList = new ArrayList<>();
        for(AssignmentsAndTeachesAndCoursesAndTeachersDTO dto1:list){
            QueryWrapper<Submissions> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("assignment_id",dto1.getAssignmentId());
            queryWrapper.eq("student_id",studentId);
            Submissions submissions = submissionsService.getOne(queryWrapper);
            AssignmentsAndTeachersAndCoursesAndTeachersAndSubmissionsDTO dto3 = new AssignmentsAndTeachersAndCoursesAndTeachersAndSubmissionsDTO();
            if(submissions != null){
                dto3.setAttachmentSubmission(submissions.getAttachment());
                dto3.setStateSubmission(submissions.getState());
                dto3.setStudentId(submissions.getStudentId());
                dto3.setGrade(submissions.getGrade());
                dto3.setFeedback(submissions.getFeedback());
                dto3.setSubDate(submissions.getSubDate());
            }
            dto3.setAssignmentId(dto1.getAssignmentId());
            dto3.setTeachId(dto1.getTeachId());
            dto3.setTitle(dto1.getTitle());
            dto3.setContent(dto1.getContent());
            dto3.setStartTime(dto1.getStartTime());
            dto3.setDueTime(dto1.getDueTime());
            dto3.setAttachment(dto1.getAttachment());
            dto3.setState(dto1.getState());
            dto3.setCourseId(dto1.getCourseId());
            dto3.setTeacherId(dto1.getTeacherId());
            dto3.setClassIds(dto1.getClassIds());
            dto3.setTeacherName(dto1.getTeacherName());
            dto3.setCourseName(dto1.getCourseName());
            dtoList.add(dto3);
        }
        // 计算分页起始和结束索引
        int startIndex = (page - 1) * size;
        int endIndex = Math.min(startIndex + size, dtoList.size());
        // 截取当前页的数据
        List<AssignmentsAndTeachersAndCoursesAndTeachersAndSubmissionsDTO> pageList = dtoList.subList(startIndex, endIndex);
        int total = dtoList.size();
        return ResultVO.success("查询成功", pageList,total);
    }

    @Override
    public ResultVO<Assignments> uploadAssignment(Integer assignmentId, Integer teachId, String title, String content, Date startTime, Date dueTime, String state, MultipartFile file) {
        try {
            Integer attachmentId = null;
            // 处理附件上传
            if (file != null && !file.isEmpty()) {
                String filename = file.getOriginalFilename();

                // 校验文件类型
                if (filename == null || !filename.toLowerCase().endsWith(".docx")) {
                    return ResultVO.fail("仅支持上传扩展名为.docx的文件");
                }
                // 解析DOCX文件为附件实体
                try {
                    Attachments attachment = DocxUtil.convertToAttachment(file);

                    // 保存附件到数据库（自动回填主键）
                    boolean saveSuccess = attachmentsService.save(attachment);
                    if (!saveSuccess) {
                        return ResultVO.fail("附件保存失败，请检查数据库连接或权限");
                    }

                    // 获取自增主键
                    attachmentId = attachment.getAttachment();

                } catch (IOException e) {
                    return ResultVO.fail("文件解析失败，可能是文件损坏或非有效DOCX格式");
                }
            }

            // 创建作业实体并校验参数
            Assignments assignment = new Assignments();
            assignment.setAssignmentId(assignmentId);
            assignment.setTeachId(teachId);
            assignment.setTitle(title);
            assignment.setContent(content);
            assignment.setStartTime(startTime != null ? startTime : new Date());
            assignment.setDueTime(dueTime);
            assignment.setState(state);
            assignment.setAttachment(attachmentId);

            // 校验必填参数
            if (assignment.getTeachId() == null) {
                return ResultVO.fail("教学ID（teachId）是必填参数，不可为空");
            }
            if (assignment.getTitle() == null || assignment.getTitle().trim().isEmpty()) {
                return ResultVO.fail("作业标题（title）是必填项，不可为空或纯空格");
            }
            if (assignment.getDueTime() == null) {
                return ResultVO.fail("截止时间（dueTime）是必填项，请选择有效时间");
            }

            // 设置默认值
            if (assignment.getStartTime() == null) {
                assignment.setStartTime(new Date()); // 默认当前时间
            }
            if (assignment.getState() == null) {
                assignment.setState("1"); // 默认未批改状态
            }
            // 保存作业记录
            boolean saveSuccess = this.save(assignment);
            return saveSuccess ? ResultVO.success("作业发布成功", assignment): ResultVO.fail("作业保存失败");

        } catch (Exception e) {
            return ResultVO.fail("发布作业时发生异常：" + e.getMessage());
        }
    }
}
